# def getText():
#     txt = open("Hamlet.txt", "r").read()
#     txt = txt.lower()
#     for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_{|} ':
#         txt = txt.replace(ch, " ")
#     return txt
#
#
# hamletTxt = getText()
# words = hamletTxt.split()
# counts = {}
# for i in words:
#     counts[words] = counts.get(words, 0) + 1
# items = list(counts.items())
# items.sort(key=lambda x: x[1], reverse=True)
# for i in range(10):
#     words, counts = items[i]
#     print("{0:<10}{1:>5}".format(words, counts))

# open()
def getText():
    file = open('D:\Hamlet.txt', 'r', encoding='utf-8')
    txts = file.read()
    # print(txts)

    # 数据预处理  数据清洗
    for i in '?,:;”’“‘!.':
        txts = txts.replace(i, ' ')

    return txts


txts = getText()
words = txts.split(' ')
counts = {}

excedes = ['', 'the', '\n', 'a', 'to', 'and', 'of']
for word in words:
    counts[word] = counts.get(word, 0) + 1
# print(counts)

# 任务：从高到低取前十位进行输出

wordvec = counts.items()
# print(list(wordvec))

txt = sorted(list(wordvec), key=lambda x: x[1], reverse=True)
for i in range(10):
    key, value = txt[i]
    print('{0:<5}{1:>5}'.format(key, value))
